import 'dart:convert';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:hbtrans_flutter/beans/home_list_bean.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';

import '../apis.dart';
import '../const.dart';
import '../routes.dart';

class Service extends StatefulWidget {
  @override
  _ServiceState createState() => _ServiceState();
}

class _ServiceState extends State<Service> {
  var homeListBean;
  List<NavigationsListBean> navigations = List();
  var loadingDialog;
  Set<String> parent_ids = Set();
  Map map = Map<String, List<NavigationsListBean>>();

  _getNews() {
    MyDio.getInstance(url: Const.TRANS_SERVER_MY_PATH).get(Apis.getNews,
        (data) {
      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }
      homeListBean = HomeListBean.fromJson(data);
      navigations = homeListBean.navigations;

      setState(() {
        for (NavigationsListBean bean in navigations) {
          parent_ids.add(bean.parentId);
        }

        for (String parent_id in parent_ids) {
          map[parent_id] = List<NavigationsListBean>();
        }

        for (NavigationsListBean bean in navigations) {
          map[bean.parentId].add(bean);
        }
      });
    });
  }

  Widget _setGrids(BuildContext context, int index) {
    List<Widget> items = List();
    if (parent_ids.length == 0) {
      return Text('没有数据');
    }

    for (String s in parent_ids) {
      items.add(Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: Column(
          children: <Widget>[
            SizedBox(
              width: MediaQuery.of(context).size.width,
              height: 44,
              child: Card(
                margin: EdgeInsets.all(0),
                color: Colors.white,
                elevation: 0,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(width: 10),
                    Text(
                      (map[s][0].levelName).split('>')[0],
                      style: TextStyle(
                          fontSize: 14, color: const Color(0xff333333)),
                    ),
                  ],
                ),
              ),
            ),
            Card(
              margin: EdgeInsets.all(0),
              child: Padding(
                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                child: _buildGrid(4, 1 / 1, map[s]),
              ),
              color: Colors.white,
              elevation: 0,
            ),
            SizedBox(
              height: 12,
            ),
          ],
        ),
      ));
    }
    return items[index];
  }

  _buildGrid(int i, var retio, List beans) {
    return GridView.count(
      // 禁止滚动
      physics: new NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      childAspectRatio: retio,
      //横轴数量 这里的横轴就是x轴 因为方向是垂直的时候 主轴是垂直的
      crossAxisCount: i,
      padding: const EdgeInsets.all(0),
      //主轴间隔
      mainAxisSpacing: 2,
      //横轴间隔
      crossAxisSpacing: 2,
      children: _setNavigations(beans),
    );
  }

  _setNavigations(List<NavigationsListBean> navigations) {
    return List.generate(
      navigations.length,
      (int index) => GestureDetector(
          onTap: () {
            MyDio.getInstance().clearInstance();
            var name = navigations[index].levelName.split('>')[1];
            if (name == '行政管理') {
              String route = '${Routes.login}';
              Routes.router.navigateTo(context, route,
                  replace: false, transition: TransitionType.fadeIn);
            } else if (name == '学时查询') {
              String route = '${Routes.classLogin}';
              Routes.router.navigateTo(context, route,
                  replace: false, transition: TransitionType.fadeIn);
            } else if (name == '学车报名') {
              String route = '${Routes.carEnroll}';
              Routes.router.navigateTo(context, route,
                  replace: false, transition: TransitionType.fadeIn);
            } else if (name == '在线学习') {
              String route = '${Routes.videoLearn}';
              Routes.router.navigateTo(context, route,
                  replace: false, transition: TransitionType.fadeIn);
            } else {
              var title = jsonEncode(Utf8Encoder().convert(name));
              var url = jsonEncode(
                  Utf8Encoder().convert(navigations[index].redirectUrl));
              String route = '${Routes.webView}?title=$title&url=$url';
              Routes.router.navigateTo(context, route,
                  replace: false, transition: TransitionType.fadeIn);
            }
          },
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.network(
                  navigations[index].pic,
                  height: 52,
                ),
                SizedBox(
                  height: 4,
                ),
                Text(
                  navigations[index].levelName.split('>')[1],
                  style: TextStyle(fontSize: 10, color: Colors.black),
                )
              ],
            ),
          )),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getNews();
  }

  @override
  void dispose() {
    super.dispose();
    MyDio.getInstance().clearInstance();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: parent_ids.length,
      itemBuilder: _setGrids,
    );
  }
}
